package cn.stylefeng.guns.modular.api.filter;



import cn.stylefeng.guns.modular.api.tips.ErrorTip;
import cn.stylefeng.guns.modular.customer.service.CustomerService;
import cn.stylefeng.guns.modular.util.JwtProperties;
import cn.stylefeng.guns.modular.util.JwtTokenUtil;

import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.roses.core.util.RenderUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 对客户端请求的jwt token验证过滤器
 *
 * @author fengshuonan
 * @Date 2017/8/24 14:04
 */
public class AuthFilter extends OncePerRequestFilter {
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    CustomerService customerService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    private final Log logger = LogFactory.getLog(this.getClass());


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "authorization,Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,token");
        System.out.println("===================================访问了" + request.getServletPath());
        //accept, authorization, token, content-type
       // chain.doFilter(request, response);
        if (request.getServletPath().startsWith("/api")) {

            final String requestHeader = request.getHeader(jwtProperties.getHeader());
            String customerId = "";
            String authToken = null;
            if (request.getServletPath().equals("/api/index") || request.getServletPath().equals("/api/getCourse") || request.getServletPath().equals("/api/login")


            ) {
                chain.doFilter(request, response);

                return;
            } else {

                if (requestHeader == null || ("").equals(requestHeader)) {
                    RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
                    return;
                }
                try{
                    customerId=jwtTokenUtil.getUsernameFromToken(requestHeader);

                    System.out.println(requestHeader+"|||||"+customerId);

                    if (customerId == null||customerId=="") {
                        //说明被拉黑了
                        RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.ACCOUNT_FREEZED.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
                        return;
                    }

                }catch (Exception e){

                    RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
                    return;
                }



                //首页可以登录可以不登录，登录就需要获取用户
                System.out.println("customer_id:"+customerId);
                request.setAttribute("customerId", customerId);
                chain.doFilter(request, response);
                return;

            }

        } else {
//            RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
            chain.doFilter(request, response);
            return;

        }

    }
}